#!/bin/bash

cd sdk
for subdir in *; do
    if [[ -d "$subdir" ]]; then
        cd "$subdir"
        echo "Renaming files in $subdir"

        # 获取当前目录下的所有.cpp文件，并按文件的创建时间进行排序
        readarray -t cpp_files < <(find . -maxdepth 1 -type f -name "*.cpp" -exec stat -c "%W %n" {} + | sort -n)

        # 打印排序后的文件列表
        count=1
        for file in "${cpp_files[@]}"; do
            filename=${file##*/}
            predict_name=$(printf "example_%03d.cpp" "$count")
            bak_name=$(printf "tmp_%03d.cpp" "$count")
            # 仅在实际名称与预期名称不一致时才修改
            if [ "$filename" != "$predict_name" ]; then
                # 如果名称已被占据，则先备份文件，第二次执行必定能修改为预期名称
                if [[ -e "$predict_name" ]]; then
                    mv "$predict_name" "$bak_name"
                    echo "Renamed $file to $bak_name"
                else
                    mv "$filename" "$predict_name"
                    echo "Renamed $file to $predict_name"
                fi
            fi
            ((count++))
        done

        # rename "example"
        cd ..
    fi
done
